<template>
  <view
    class="w-full pt-[var(--top-m)] min-h-screen bg-page personal-wrap !pb-[20rpx]"
    :style="themeColor()"
  >
    <view class="sidebar-margin overflow-hidden card-template py-[20rpx]">
      <u-cell-group :border="false" class="cell-group">
        <u-cell
          title="支付密码"
          :titleStyle="{ 'font-size': '28rpx' }"
          :is-link="true"
          :value="payPwdSet ? '已设置' : '未设置'"
          @click="openSetDialog"
        ></u-cell>
        <u-cell
          v-if="payPwdSet"
          title="找回支付密码"
          :titleStyle="{ 'font-size': '28rpx' }"
          :is-link="true"
          @click="openRecoverDialog"
        ></u-cell>
      </u-cell-group>
    </view>

    <view class="sidebar-margin overflow-hidden card-template py-[20rpx] mt-[20rpx]">
      <view
        class="px-[24rpx] py-[12rpx] text-[26rpx] text-[var(--text-color-light6)] leading-[42rpx]"
      >
        <view class="mt-[8rpx]">支付密码将用于以下场景：</view>
        <view class="mt-[8rpx]">· 可用积分转换兑换券</view>
        <view>· 可用积分互转</view>
        <view>· 余额支付</view>
        <view>· 兑换券兑换商品</view>
        <view>· 购买星星豆</view>
        <view>· 兑换星星豆</view>
      </view>
    </view>

    <u-popup
      :show="setDialogShow"
      mode="center"
      :safeAreaInsetBottom="true"
      @close="setDialogShow = false"
    >
      <view class="p-[40rpx]">
        <view class="text-[32rpx] text-[#333] font-500 mb-[20rpx]">
          {{ payPwdSet ? "修改支付密码" : "设置支付密码" }}
        </view>
        <u-form
          :model="setForm"
          ref="setFormRef"
          labelPosition="top"
          labelWidth="180rpx"
          errorType="toast"
        >
          <u-form-item
            v-if="payPwdSet"
            prop="old_password"
            label="旧密码"
            :border-bottom="false"
          >
            <u-code-input v-model="setForm.old_password" :space="4" :maxlength="6" dot />
          </u-form-item>

          <u-form-item label="新密码" prop="password" :border-bottom="false">
            <u-code-input v-model="setForm.pay_password" :space="4" :maxlength="6" dot />
          </u-form-item>

          <u-form-item label="确认密码" prop="confirm_password" :border-bottom="false">
            <u-code-input
              v-model="setForm.confirm_password"
              :space="4"
              :maxlength="6"
              dot
            />
          </u-form-item>
        </u-form>
        <view class="mt-[40rpx]">
          <button
            class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff]"
            @click="submitSet"
          >
            确定
          </button>
        </view>
      </view>
    </u-popup>

    <u-popup
      :show="recoverDialogShow"
      mode="center"
      :safeAreaInsetBottom="true"
      @close="recoverDialogShow = false"
    >
      <view class="p-[40rpx]">
        <view class="text-[32rpx] text-[#333] font-500 mb-[20rpx]">找回支付密码</view>
        <u-form
          :model="recoverForm"
          ref="recoverFormRef"
          labelPosition="top"
          labelWidth="180rpx"
          errorType="toast"
        >
          <view
            class="h-[88rpx] px-[20rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6] mb-[20rpx]"
          >
            <u-form-item prop="mobile" :border-bottom="false">
              <u-input
                v-model="recoverForm.mobile"
                type="number"
                maxlength="11"
                border="none"
                placeholder="请输入手机号"
                fontSize="26rpx"
                placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]"
              />
            </u-form-item>
          </view>
          <view
            class="h-[88rpx] px-[20rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6] mb-[20rpx]"
          >
            <u-form-item prop="mobile_code" :border-bottom="false">
              <u-input
                v-model="recoverForm.mobile_code"
                type="number"
                maxlength="6"
                border="none"
                placeholder="请输入短信验证码"
                fontSize="26rpx"
                placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]"
              >
                <template #suffix>
                  <sms-code
                    :mobile="recoverForm.mobile"
                    type="find_pay_pass"
                    v-model="recoverForm.mobile_key"
                  ></sms-code>
                </template>
              </u-input>
            </u-form-item>
          </view>
          <u-form-item v-if="recoverForm.mobile_key" prop="pay_password" label="新密码" :border-bottom="false">
            <u-code-input
              v-model="recoverForm.pay_password"
              :space="4"
              :maxlength="6"
              dot
            />
          </u-form-item>
          <u-form-item v-if="recoverForm.mobile_key" prop="confirm_pay_password" label="确认密码" :border-bottom="false">
            <u-code-input
              v-model="recoverForm.confirm_pay_password"
              :space="4"
              :maxlength="6"
              dot
            />
          </u-form-item>
        </u-form>
        <view class="mt-[40rpx]">
          <button
            class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff]"
            @click="submitRecover"
          >
            验证并重置
          </button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup lang="ts">
import useMemberStore from "@/stores/member";
import { setPayPassword, updatePayPassword, resetPayPassword } from "@/app/api/auth";
// import { useLogin } from '@/hooks/useLogin'
import { ref, reactive, computed, getCurrentInstance } from "vue";

const memberStore = useMemberStore();
const instance = getCurrentInstance();
const themeColor = () => (instance?.proxy as any)?.themeColor?.() || {};

const payPwdSet = computed(() => {
  const info: any = memberStore.info || {};
  return !!(info && info.pay_password);
});

const setDialogShow = ref(false);
const setForm = reactive({ old_password: "", pay_password: "", confirm_password: "" });
const setFormRef: any = ref(null);

const recoverDialogShow = ref(false);
const recoverForm = reactive({
  mobile: "",
  mobile_key: "",
  mobile_code: "",
  pay_password: "",
  confirm_pay_password: "",
});
const recoverFormRef: any = ref(null);

// 打开找回支付密码弹窗
const openRecoverDialog = () => {
  recoverDialogShow.value = true;
  recoverForm.mobile = (memberStore.info && (memberStore.info as any).mobile) || "";
  recoverForm.mobile_key = "";
  recoverForm.mobile_code = "";
  recoverForm.pay_password = "";
  recoverForm.confirm_pay_password = "";
};

// 验证手机号
const isMobile = (val: string) => {
  const test = (uni as any)?.$u?.test?.mobile;
  return typeof test === "function" ? test(val) : /^1[3-9]\d{9}$/.test(val);
};

// 提交找回支付密码
const submitRecover = () => {
  if (!isMobile(recoverForm.mobile)) {
    uni.showToast({ title: "请输入正确手机号", icon: "none" });
    return;
  }
  if (!recoverForm.mobile_key || !recoverForm.mobile_code) {
    uni.showToast({ title: "请输入短信验证码", icon: "none" });
    return;
  }
  if (!/^\d{6}$/.test(recoverForm.pay_password)) {
    uni.showToast({ title: "请输入6位新支付密码", icon: "none" });
    return;
  }
  if (recoverForm.pay_password !== recoverForm.confirm_pay_password) {
    uni.showToast({ title: "两次输入的密码不一致", icon: "none" });
    return;
  }
  uni.showLoading({ title: "" });
  try {
    resetPayPassword({
      mobile: recoverForm.mobile,
      mobile_key: recoverForm.mobile_key,
      mobile_code: recoverForm.mobile_code,
      pay_password: recoverForm.pay_password,
    }).then((res) => {
      memberStore.getMemberInfo();
      uni.showToast({ title: "重置成功", icon: "success" });
      recoverDialogShow.value = false;
    });
  } finally {
    uni.hideLoading();
  }
};

// 打开设置支付密码弹窗
const openSetDialog = () => {
  setDialogShow.value = true;
  setForm.old_password = "";
  setForm.pay_password = "";
  setForm.confirm_password = "";
};

// 提交设置支付密码
const submitSet = () => {
  if (payPwdSet.value && !setForm.old_password) {
    uni.showToast({ title: "请输入旧支付密码", icon: "none" });
    return;
  }
  if (!/^\d{6}$/.test(setForm.pay_password)) {
    uni.showToast({ title: "请输入6位新支付密码", icon: "none" });
    return;
  }
  if (setForm.pay_password !== setForm.confirm_password) {
    uni.showToast({ title: "两次输入的密码不一致", icon: "none" });
    return;
  }
  uni.showLoading({ title: "" });
  try {
    if (payPwdSet.value) {
      updatePayPassword({
        old_pay_password: setForm.old_password,
        new_pay_password: setForm.pay_password,
      }).then((res) => {
        memberStore.getMemberInfo();
        uni.showToast({ title: "已修改", icon: "success" });
        setDialogShow.value = false;
      });
    } else {
      setPayPassword({
        pay_password: setForm.pay_password,
      }).then((res) => {
        memberStore.getMemberInfo();
        // useLogin().handleLoginBack();
        uni.showToast({ title: "设置成功", icon: "success" });
        setDialogShow.value = false;
      });
    }
  } finally {
    uni.hideLoading();
  }
};
</script>

<style lang="scss" scoped>
page {
  background: var(--page-bg-color);
}
:deep(.u-input) {
  background-color: transparent !important;
}
:deep(.u-line) {
  display: none !important;
}
</style>
